Python類的屬性 學習筆記

2021-10-06 13:45:04 字數 1716 閱讀 2960

屬性本質是方法,使用像字段

person.py

import datetime

class

person

:def

__init__

(self, name=

'', birthdate, gender=

'男', salary=

0)

self.name = name

self.age = birthdate

self.gender = gender

self.salary = salary

//self._salary //_開頭表示私有

@property

//裝飾器

defsalary

(self)

://外部訪問

return self._salary

@salary.setter

defsalary

(self, value)

:if value <=0:

self._salary =

0else

: self._selary = value

defget_age

(self)

:return datetime.date.today(

).year - self.birthdate.year

@property

defage

(self)

://本質是方法,使用像字段

return datetime.date.today(

).year - aelf.birthdate.year

@age.setter

defage(self, value)://

raise valueerror(

'年齡不能賦值,只能通過生日計算!'

)print

('您賦的值是:'

, value)

print

('年齡是通過生日計算的,不能手動賦值!'

)def

say(self, word)

:print

("{} say: {}"

.format

(self.name, word)

)def

__str__

(self)

:return f''

>>

>

import person

>>

>p = person(

'tom'

, datetime.date(

1990,3

,3))

>>

>

print

(p.age)

30//屬性預設下不能賦值,如果要賦值要寫乙個setter

//>>

>p.age =

30//attributeerrpe: can't set attribute

//>>

>p.age =

30valueerror: 年齡不能賦值,只能通過生日計算

>>

>p.age =

30您賦的值是:30

年齡是通過生日計算的,不能手動賦值!

Python學習筆記 類 類方法 類屬性

類 類方法 類屬性練習 class student company xx大學 類屬性 count 0 類屬性 def init self,name,score 初始化 給各屬性賦值 self.name name 例項屬性 self.score score student.count 1def say...

Python筆記 物件屬性和類的屬性

class person object type 人類 這個屬性定義在類裡,函式之外,我們稱之為類屬性 def init self,name,age self.name name self.age age 物件p1,p2都是通過person類建立出來的例項物件 name和age是物件屬性,是每乙個例...

python學習筆記 類屬性 例項屬性

上篇 class tool object 類屬性 num 0 方法 def init self,name 例項屬性 self.name name tool.num 1 tool1 tool a 例項物件 tool2 tool b 例項物件 tool3 tool c 例項物件 類屬性 num 0 例項...