환웅 데이터

[Python] Object / Attribute 본문

카테고리 없음

[Python] Object / Attribute

환 웅 2025. 3. 17. 09:17

 
 
Class: 제품의 설계도. Defines how objects of a particular type behave.
Class Statement: Creates a new class and binds thay class to <name> in the first frame of current environment.
def statement과는 차이가 있음. 
Object: 설계도로 만든 작품. 
Attribute: class 내부의 변수. Object's attributes are accessed and modified using dot expressions.
존재하는 속성값은 언제든지 바꿀 수 있음

>>> a = Account('Alan')
>>> a.balance
0
>>> a.balance = 12
>>> a.balance
12
# the value of an existing attribute can be changed any time

정의되어 있지 않은 새로운 attribute name을 정의하는 것도 가능함

>>> b = Account('Ada')
>>> b.balance 
0
>>> b.balance = 20
>>> a.backup = b # new attribute
>>> a.backup.balance # b.balance랑 똑같음
20

 
Instance Attribute: Instance에서 정의된 attribute
Class Attirbute: class에서 정의된 attribute
 
Method: class 내부의 함수. object에 대해 특정 연산을 수행하는 함수입니다. A function called on an object using a dot. Method is defined in a class statement.
Dot notation automatically supplies the first argument to a method: 예시에선 tom_account가 self로 bound.

class Account:
    def deposit(self, amount):
        self.balance = self.balance + amount
        return self.balance
        
>>> tom_account = Account('Tom')
>>> tom_account.deposit(100)
100

 
Bound method: object + Function 

>>> type(Account.deposit)
<class 'function'> # look up method using its class gives function
>>> type(tom_account.deposit)
<class 'method'> # look up method using an instance of account class gives bound method

>>> Account.deposit(tom_account, 1001) # two arguments because it is function
1011
>>> tom_account.deposit(1007) # tom_account automatically fills in self argument
2018

 
Dot Expression <expression>.<name> : Methods are invoked using dot notation.
s.append(5). append is the method here. method is specific to a particular object, s. 이것도 dot exp가 맞나?
name은 먼저 instance에서 찾고, 없으면 class에서 찾을 것?
 
getattr: can look up an attribute using a string
hasattr: whether an attribute of this name exits either for instance(Tom_account) or its class

>>> tom_account.balance
10

>>> getattr(tom_account, 'balance')
10
>>> hasattr(tom_account, 'deposit')
True

 
Instance: object에 포함된 개념. class는 하나지만, class에 대한 각각의 호출은 제각각 새로운 instance를 생성할 것.
__init__ : Special method name for the function that constructs an instance. (Constructor 라고 불리기도 함)
 

class class_name:
    def method_name(self):
        command
        
class Monster:
    def say(self):
        print("I'm a monster")
        
object = classname() #class로부터 object를 만든다
object.method() #.은 ~의 라는 뜻. object의 method

shark = Monster()
shark.say()

class Monster:
    def __init__(self, name): #첫번째 매개변수는 자기 자신, 두번째는 보통 attribute
    self.name = name # object자기 자신의 속성은 init으로 부터 받은 name으로 할당
    # 즉, self.name은 Monster의 attribute
    def say(self):
        print(f"I'm {self.name")
        
shark = Monster("Shark") #"Shark"는 name 자리에 들어감
# shark는 self에 들어감