Basic Python

Class, pass, instance, binding, Object, variable, self, method, __init__, dir, namespace, __dict__, __del__

Naranjito 2021. 4. 20. 18:15
  • Class

Basic cookie frame. The meaning of defining the class is defining the new data type. It is a set or category of things having some property of attribute in common and differentiated from others by kind, type, or quality. A blue print for individual objects.

class BusinessCard:
    pass

pass : It can be defined the class without anything inside the class.

 

  • instance

Shaped cookie, result through cookie frame. In order to use new data type(The meaning of defining the class is defining the new data type), it requires to create instance. Add () after name of class.

card1=BusinessCard()
card1
>>>
<__main__.BusinessCard at 0x111916100>

type(card1)
>>>
__main__.BusinessCard #card1 belongs to BusinessCard class

card1 : instance

binding : variable indicating the location of instance of the class

 

  • Object

It is one of instances of the class which can perform the functionalities which are defined in the class.

 

  • variable
card1=100
id(card1)
>>>
4589707520

 

 

 

  • self

It represents the instance of the class. By using this, we can access the attributes and methods of the class.

Let's say when func2 called, call the identity of self.

class Foo:
    def func1():
        print('fun1')
    def func2(self):
        print(id(self))
        print('fun2')

And then, let's compare the the identity between id(self) and new instance after create new instance.

First, identity of id(self).

f.func2()
>>>
4582802096

Second, identity of new instance.

f=Foo()
id(f)
>>>
4582802096

 

They are same. In other words, self is same as class instance.

 

  • method

- Diferrence calling the method between through the instance and class name? They are same.

#create new object and it is indicating to f3, new instance
f3=Foo()

#call the method through the instance
f3.func2()
>>>
4583189808
fun2

#call the method through class name
Foo.func2(f3)
>>>
4583189808
fun2

 

  • __init__

Initialize, is known as a constructor in object. It called when an object is created from the class and it allows the class to initialize the attributes of a class. Create the instance and input the value at the same time.

class BusinessCard:
    def __init__(self, name, email, addr): # set_info has been changed to __init__
        self.name=name
        self.email=email
        self.addr=addr

    def print_info(self):
        print('name:', self.name)
        print('email:', self.email)
        print('address:', self.addr)

__init__ : constructor, has been changed from set_info.

And then, 

card1=BusinessCard("Yuna Kim", "yunakim@naver.com", "Seoul")
card1.print_info()
>>>
name: Yuna Kim
email: yunakim@naver.com
address: Seoul

In other words,  storing the instance variable and create the instance at the same time by using initialized class.

                                           2.                                               1.
initialized class<--3 parameters(nameemailaddr)<--constructor 〉 instance variable
(BusinessCard)  ⇡receiving                                        ⇡from            ⇡storing


            instance()<--instance method
created (card1)   ⇡calling-->instance variable
      3.                            4.     ⇡print
                                                   5.

Instead of,

member1.set_info("Yuna Kim", "yunakim@naver.com", "Seoul")
member1.print_info()
>>>
name: Yuna Kim
email: yunakim@naver.com
address: Seoul
class Rectange: #object
   def __init__(self, length, breadth, unit_cost=0): #attribute
       self.length = length
       self.breadth = breadth
       self.unit_cost = unit_cost
   
   def get_perimeter(self): #self used as a parameter in the method
       return 2 * (self.length + self.breadth)
   
   def get_area(self): #method
       return self.length * self.breadth
   
   def calculate_cost(self): #method
       area = self.get_area()
       return area * self.cost
# breadth = 120 cm, length = 160 cm, 1 cm^2 = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s cm^2" % (r.get_area()))
print("Cost of rectangular field: Rs. %s ", %(r.calculate_cost()))

- length, breadth : attributes

- get_perimeter, get_area, calculate_cost : methods

- length : It is bind to the object at the time of object creation

- r : works like self, instance of the class, the representation of the object outside the class

- get_perimeter(self), get_area(self), calculate_cost(self) : self used as a parameter in the method, it automatically passes as a first argument along with other arguments. Call the method inside the class. The representation of the object inside the class.

 

reference : micropyramid.medium.com/understanding-self-and-init-method-in-python-class-c9018db5fc8a

 

Another example : 

class Dog:
    animal:'Dog' #variable

    def __init__(self, breed, color): # case 1: init + self should be always more than 2arguments including self
    # case 2: def __init__(self, r=0, i=0)
    # case 3: def fun(self)
    # case 4: def setColor(self, color)

        # case 1
        self.breed=breed # instance variable
        self.color=color # (self, breed, color) <--<breed, color> should be defined in here as self.breed, self.color

        # case 2
        self.real=r 
        self.imag=i 

        # case 3
        Rodger.fun() # Or
        Dog.fun()

        # case 4
        self.color=color # It is going to be a Dog color

# case 1
Rodger = Dog("Pug", "brown") # (self, breed, color) <--<breed, color> should be defined in here as Dob(#,#)
Buzo = Dog("Bulldog", "black")

# case 2
num=Dog(2,3)

# case 3
Rodger=Dog()

# case 4
Rodger.setColor('brown')

 

  • __del__

It happens after instance of class has been deleted

 

  • dir

Directory, it returns a list of valid attributes of the object.

class Stock:
    market='kospi'
dir()
>>>
['Stock', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

 

  • namespace

Once class defined, namespace is created simultaneously. And variable or method defined within the class is storing as dictionary type.

When there is none of variable nor method in the namespace of the instance, it refers class namespace.

 

  • __dict__

It returns the namespace attributes as a dictionary type. 

Stock.__dict__
>>>
mappingproxy({'__module__': '__main__',
              'market': 'kospi',
              '__dict__': <attribute '__dict__' of 'Stock' objects>,
              '__weakref__': <attribute '__weakref__' of 'Stock' objects>,
              '__doc__': None})

So, that's why I can access the variable of class.

Stock.market
>>>
'kospi'