본문 바로가기
IT World/Python

Python Training Day 6. Classes and Objects

by 닷라인웨이 2022. 12. 17.

Chapter 9. Classes and Objects (learnpython.org)

 

Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes.

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()


# -------Accessing Object Variables-------

myobjectx.variable

print(myobjectx.variable)
class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

'''You can create multiple different objects that are of the same class(have the same variables and functions defined). 
However, each object contains independent copies of the variables defined in the class.'''

myobjectx = MyClass()
myobjecty = MyClass()

myobjecty.variable = "yackity"

# Then print out both values
print(myobjectx.variable)
print(myobjecty.variable)
class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")
        
# -------Accessing Object Functions-------

myobjectx = MyClass()

myobjectx.function()

init()

The __init__() function, is a special function that is called when the class is being initiated. It's used for assigning values in a class.

class NumberHolder:

   def __init__(self, number):
       self.number = number

   def returnNumber(self):
       return self.number

var = NumberHolder(7)
print(var.returnNumber()) #Prints '7'

 

Exercise

 

Java의 Class 개념을 알고 있으면 이해하기 좀 더 수월한 듯 하다.

'IT World > Python' 카테고리의 다른 글

Python Training Day 8. Modules and Packages  (0) 2022.12.19
Python Training Day 7. Dictionaries  (0) 2022.12.18
Python Training Day5. Functions  (0) 2022.12.16
Python Training Day4. Loops  (0) 2022.12.15
Python Training Day3. Conditions  (0) 2022.12.14

댓글