程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[learn Python from simple to deep] definition and use of object-oriented class 1

編輯:Python

1. Classes and objects :

(1) Class is a general term for something , The object is a real object . for example : Animals are a class , Dogs and cats are objects .
(2) Class through instantiation , Get the object

2. The definition of a class :

(1) Class has properties and methods
(2)__init__ Method is a special method , Every time you create an object with a class , Will automatically run this method .
The name of the method , There are two underscores at the beginning and two underscores at the end , It's an agreement , Avoid conflicts with other common method names
(3) Parameters self Is a reference to the object itself , Whether the object can access the properties and methods in the class .
self It is an automatic transfer without manual transfer , So when creating objects from classes , Just give the following formal parameters (name,age) Provide value .

# Defining classes 
class Animal:
# Define the properties of the class : By construction method 
def __init__(self,name,age):
self.name=name
self.age=age
# Define the methods of the class 
def sit(self):
# Simulate the animal being ordered to sit down 
print(self.name + " is now sitting")
# Instantiation 1—— Get objects through classes 
dog=Animal('Xiaohua',3)
print(dog.name)
print(dog.age)

Xiaohua
3

# Instantiation 2—— Get other objects 
cat=Animal('Xiaomao',2)
cat.name

‘Xiaomao’

cat.sit()

Xiaomao is now sitting


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved