2016-10-14 4 views
1

속성의 인스턴스가 이미 내 개체에 있는지 확인하려고합니다. 아래에서 볼 수 있듯이 내 Dog 개체에 do_something_if_has_aged 메서드를 통해 특정 특성이있는 경우 무언가를 수행하려고합니다. 특정 속성이 이미 선언되었는지 여부를 어떻게 확인할 수 있습니까? 하지만,메소드가 이미 객체에 있는지 확인하십시오.

>>> class Dog: 
    def __init__(self, name, age): 
     self.name = name 
     self.age = age 
    def add_years(self, years): 
     self.age += years 
     self.has_aged = True 
    def do_something_if_has_aged(self): 
     if self.has_aged: 
      print("The dog has aged and is %d years closer to death" % self.years) 
     else: 
      print("The dog hasn't aged, apparently.") 


>>> dog = Dog('Spot', 3) 
>>> dog.age 
3 
>>> dog.do_something_if_has_aged() 
Traceback (most recent call last): 
    File "<pyshell#193>", line 1, in <module> 
    dog.do_something_if_has_aged() 
    File "<pyshell#190>", line 9, in do_something_if_has_aged 
    if not self.has_aged: 
AttributeError: 'Dog' object has no attribute 'has_aged' 
>>> dog.add_years(1) 
>>> dog.age 
4 
>>> dog.do_something_if_has_aged() 
The dog hasn't aged, apparently. 

분명히 개 세했습니다

obj = None 
if obj: 
    print(True) 
else: 
    print(False) 

가 여기 내 최소 재현 예제 : 일반적으로 당신은 False을 반환이 같은과 존재를 확인한다.

제목이 내가 아래에서 전달하려고하는 것을 반영하지 않으면 사과드립니다. 나는 OOP에 처음 온 사람이다.

+1

조건이 잘못되었습니다. 'if self.has_aged'를 수행해야합니다. –

답변

3

오히려 시험 F보다 또는 속성에서 클래스에 대한 기본값을 설정합니다.

class Dog: 
    has_aged = False # default for all instances 
    def __init__(self, name, age): 
     self.name = name 
     self.age = age 
    def add_years(self, years): 
     self.age += years 
     self.has_aged = True # sets an instance attribute 
    def do_something_if_has_aged(self): 
     if self.has_aged: 
      print("The dog has aged and is %d years closer to death" % self.years) 
     else: 
      print("The dog hasn't aged, apparently.") 

(주 내가 self.has_aged사실이 첫 번째 지점으로 가고 싶은 경우, 테스트를 반전해야한다고이 아닌 다른 방법 : 파이썬 누락 된 인스턴스 속성 대신 클래스 속성을 찾습니다 경우 약).

아니면 __init__의 속성에 대한 기본값을 설정할 수 있습니다

class Dog: 
    def __init__(self, name, age): 
     self.name = name 
     self.age = age 
     self.has_aged = False 
    def add_years(self, years): 
     self.age += years 
     self.has_aged = True 
    def do_something_if_has_aged(self): 
     if self.has_aged: 
      print("The dog has aged and is %d years closer to death" % self.years) 
     else: 
      print("The dog hasn't aged, apparently.") 
속성이 hasattr() function에 존재하는 경우도 테스트 할 수 있습니다

:

def do_something_if_has_aged(self): 
    if hasattr(self 'has_aged') and self.has_aged: 
     print("The dog has aged and is %d years closer to death" % self.years) 
    else: 
     print("The dog hasn't aged, apparently.") 

또는 getattr() function를 사용하여 기본값 :

def do_something_if_has_aged(self): 
    if not getattr(self 'has_aged', False): 
     print("The dog has aged and is %d years closer to death" % self.years) 
    else: 
     print("The dog hasn't aged, apparently.") 

그러나, 속성에 대해 동적으로 테스트하는 것은 사용자가 선택한 첫 번째 옵션이 아니어야합니다. 클래스 기본값을 갖는 것이 훨씬 깔끔합니다.

+0

'has_aged'가 ('__init__'에 정의 된) 인스턴스 변수 대신에 클래스 변수가된다는 점은 무엇입니까? –

+1

@ JosieThompson : 변수 복사본이 하나만 있으므로 (메모리 이점); 디폴트가 클래스에 저장 될 수있을 때 모든 인스턴스에 속성을 부여하는 이유는 무엇입니까? –

4

당신이 hasattr 내장 기능을 찾고있는 것 같습니다 : 귀하의 경우

>>> class Dog(object): 
...  pass 
... 
>>> a = Dog() 
>>> hasattr(a, 'age') 
False 
>>> a.age = 7 
>>> hasattr(a, 'age') 
True 

, 당신은 수정할 수 있습니다 다음과 같이

def do_something_if_has_aged(self): 
    if hasattr(self, 'has_aged'): 
     pass # do your logic 
1

내가 포함하도록 __init__ 방법을 다시 것 self.has_aged = False 검사하지 않아도됩니다.

class Dog(object): 
    def __init__(self, name, age): 
     self.name = name 
     self.age = age 
     self.has_aged = False # Starting value so it is guaranteed to be defined (unless explicitly deleted). 

이제 수업의 나머지 부분은 서면으로 작동해야합니다. hasattr를 사용하여 완벽하게 정상적으로 경우

class Foo(object): 
    def set_bar(self): 
     self.bar = True # Define the attribute bar if it is not yet defined. 

    def is_bar_set(self): 
     return hasattr(self, 'bar') 
1

확인하기 위해,하지만 경우에 당신은 당신을 위해 빠른 수정을 찾고 있습니다 : 당신은 속성이 객체에 정의되어 있는지 확인하려는 경우, 당신은이를 쓸 수 있습니다 코드, 당신은 손 전에 거짓으로 변수를 초기화 할 수 있습니다

class Dog: 
    has_aged = False 

을 그리고 난 그것을 반대해야한다고 생각으로도 당신의 상태를 수정 :

def do_something_if_has_aged(self): 
    if self.has_aged: # instead of not self.has_aged 
    print("The dog has aged and is %d years closer to death" % self.years) 
    else: 
    print("The dog hasn't aged, apparently.") 
관련 문제