Get the App
SLTechnology News&Howtos  ›  Development  › 

How python defines classes

Shulou Source: shulou.com Published: 2022-06-01 03:05:54 09月16日 Update

This article will explain in detail how to define classes in python. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Common method

There are two ways to create a common method (class A () & class B ()).

Class A (): def _ init__ (self, name, age): self.name = name self.age = age def get_name (self): print ('my name is', self.name) def get_age (self): print (Flemi am {self.age} years old') class B (): def get_name (self, name): print ('my name is', name) def get_age (self Age): print (Flemi am {age} years old') if _ _ name__ ='_ _ main__': a = A ('tom',19) a.get_name () # my name is tom a.get_age () # I am 19 years old b = B () b.get_name (' tom') # my name is tom b.get_age (19) # I am 19 years old

In class A (), _ _ init__ () is a special method, which is equivalent to initializing A. the self in _ _ init__ is the object An itself, and name and age are their formal parameters.

The class needs to be instantiated before each method call

This is the end of this article on "how to define classes in python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Methods articles ordinary more good practical special content examples objects articles methods knowledge formal parameters references help related Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Xiaomi Shulou Information Apple OPPO Reno