Class

decal·2023년 1월 10일
0

study notes

목록 보기
8/12

class:

  • to group data and functionality
  • a template to create many similar but distinct things
class NameOfClass:

instances:

  • creating variables from the class template

definition:

  • name of class that we're creating variables from

To create an instance and store it in a variable:

class Pokemon:
	name = "squirtle"
    
pokemon = Pokemon()

To access a class variable:
print(variable.instance)

class Virtual_Pet:
	wagging_tail = True
    color = "brown"

skippy = Virtual_Pet()
print(skippy.wagging_tail)

Output: True

another example:

class Pokemon:
	name = "squirtle"
    weight = "19.8"
    
pokemon = Pokemon()
print(pokemon.name)
print(pokemon.weight)

Output:

squirtle
19.8

methods:

  • functions that classes have (functions inside a class)

self:

  • a special keyword that we need to use inside class definition
  • we pass 'self' as the first parameter to all the methods we add

For example:

class Virtual_Pet:
	color = "brown"

	def bark(self):
    	print("Bark")

rocky = Virtual_Pet()
rocky.bark()

We use 'self' as a parameter in class methods so that we can access the class variables inside methods.

For example:

class Virtual_Pet:
	color = "brown"
    legs = 4

	def bark(self):
    	print("Bark")
        
    def display_color(self):
    	print(self.color)
        
    def display_legs(self):
    	print(self.legs)

rocky = Virtual_Pet()
rocky.display.color()
rocky.display.legs()

Output:

brown
4

If we don't use 'self', we cannot access the class variables because they are declared outside of the class method's scope.


To use a class method:
variable.method()

For example:

class Virtual_Pet:
	color = "brown"
    
    def bark(self):
    	print("Bark")

rocky = Virtual_Pet()

print(rocky.color)
rocky.bark()

Output:

brown
Bark

Access and call the method 'introduce' using the class instance 'pikachu':

class Pokemon:
	name = "pikachu"
    
    def introduce(self)
    	print("Hi!")
        print("I am " + self.name)
        
pikachu = Pokemon()
pikachu.introduce()

Output:

Hi!
I am pikachu

Display pikachu's color variable in the console:

class Pokemon:
	name = "pikachu"
    color = "yellow"
    
    def introduce(self)
    	print("Hi!")
        print("I am " + self.name)
        
pikachu = Pokemon()
pikachu.introduce()
print(pikachu.color)

Output:

Hi! 
I am pikachu 
yellow

0개의 댓글