Data Science Explorer

[Basic Grammar] Python Classes/Objects 본문

Python

[Basic Grammar] Python Classes/Objects

grace21110 2023. 11. 19. 12:11
반응형

A class is like an object constructor, blueprint for creating objects. 

 

Example 

Create a class named MyClass, with a proprty named x: 

class MyClass:
	x = 10

 

  • Create Object 

Example 

Create an object named p1, and print the value of x: 

p1 = MyClass ()
print (p1.x)

 

  • The __init__() Function

All classes have a function called __init__(), which is always executed when the class is being initiated. 

Example 

Create a class named Chirstmas, use the __init__() function to assign values for gift and price:

Class Christmas 
	def __init__(self, gift, price):
    self.gift = gift
    self.price = price 
    
  
 p1 = Christmas ("Grace", 23)
 
 print (p1.gift)
 print(p1.age)

 

  • The __str__() Function 

This function controls what should be returned when the class object is represeted as a string. 

I will show you the difference when you use the __str__() function and don't use it.

 

Example 

With __str__()

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def __str__(self):
    return f"{self.name}({self.age})"

p1 = Person("Grace", 24)

print(p1)
Grace(24)

Example 

Witouth __str__()

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("Grace", 24)

print(p1)
<__main__.Person object at 0x15039e602100>

 

  • Object Methods 

Class can also contain methods and they belong to the object. 

Example

Class Christmas 
 	def __init__ (self, gift, price) 
    self.gift = gift 
    self.price = price 
   
    def myfunc(self): 
    print ("I want to get " + self.gift)
    
p1 = Christmas ("gloves", 20)
p1.myfunc()

 

  • The self parameter 

It is a reference to the current instance of the class, and is used to access variables that belong to the class. 

It does not have to be named self, you can name it whatever you like, however, it has to the first parameter of any function in the class. 

 

  • The pass statement 

Class definitions cannot be empty, but if you for some reason have a class definition with no content, putthe pass statement to avoid getting an error.

class Christams:
	pass

 

  • Delete Object Properties 

You can delete properties on objects by using the del keyword 

del p1.gift

 

  • Delete Object itself 

You can delete the object 

del p1

 

  • Modify Object properties 
p1.price = 40

'Python' 카테고리의 다른 글

[Basic Grammar] Modules  (1) 2023.11.22
[Basic Grammar] Python Inheritance  (0) 2023.11.21
Matplotlib Pie Charts  (0) 2023.11.11
Matplotlib Histograms  (0) 2023.11.10
Matplotlib Bars  (2) 2023.11.09