Python Basics----Properties, static methods (Staticmethod), class methods (Classmethod), __str__ usage

Source: Internet
Author: User
Tags class definition throw exception

Read Catalogue

  • First, characteristics (property)
  • Second, static method (Staticmethod)
  • Iii. class Methods (Classmethod)
  • Iv. usage of additional knowledge points __str__
Back to Top First, characteristics (property)

1 What is attribute property

property is a special attribute that performs a function (function) and then returns a value when it is accessed

1 Import Math 2 class Circle:3     def __init__ (Self,radius): #圆的半径radius 4         Self.radius=radius 5  6     @ Property 7     def area (self): 8         return Math.PI * self.radius**2 #计算面积 9     @property11     def perimeter (self) :         2*math.pi*self.radius #计算周长13 c=circle (c.radius) print (C.area) #可以向访问数据属性一样去访问area, Triggers the execution of a function that dynamically calculates a value of print (c.perimeter) #同上18 ' 19 output: 20 314.159265358979321 62.8318530717958622 "

Note: Attributes Arear and perimeter cannot be assigned at this time

C.area=3 #为特性area赋值 ' Throw exception: Attributeerror:can ' t set attribute '

2 Why should I use the property

After the function of a class is defined as an attribute, when the object is Obj.name, it is impossible to realize that its name is executed by a function and then computed, and that the use of this feature follows the principle of uniform access .

Besides, look at the

PS: Object-oriented encapsulation There are three ways: "Public" this is actually not encapsulated, is open to the external "protected" This packaging method is not public, but to friends (friend) or sub-class (the image is "son", but I do not know why people do not say "daughter", like "Parent" is meant to be "parents", but Chinese is called "father") public "private" this package is not open to anyone

Python does not have the syntax to build three of them into its own class mechanism, in C + + will generally be all the data is set to private, and then provide set and get method (interface) to setup and fetch, in Python through the property method can be implemented

1 class Foo:2     def __init__ (self,val): 3         self.__name=val #将所有的数据属性都隐藏起来 4  5     @property 6     def NAME ( Self): 7         return self.__name #obj. Name accesses the Self.__name (which is also where the real value is stored) 8  9     @name. Setter10     def NAME (self, Value):         isinstance (VALUE,STR):  #在设定值之前进行类型检查12             raise TypeError ('%s must be str '%value) 13         Self.__name=value #通过类型检查后, store the value values in the real location self.__name14     @name. Deleter16     def NAME (self): 17         Raise TypeError (' Can not delete ') F=foo (' Egon ') "Print (f.name) # f.name=10 #抛出异常 ' typeerror:10 must be str ' 2 2 del f.name #抛出异常 ' typeerror:can not delete '
1 class Foo:2     def __init__ (self,val): 3         self.__name=val #将所有的数据属性都隐藏起来 4  5     def getname (self): 6         Return self.__name #obj. NAME accesses the Self.__name (which is also where the real value is stored) 7  8     def setname (self,value): 9         if not isinstance (VALUE,STR):  #在设定值之前进行类型检查10             raise TypeError ('%s must be str '%value)         self.__name=value #通过类型检查后, Store value values in the real place self.__name12     def delname (self):         raise TypeError (' Can not delete ')     name= Property (Getname,setname,delname) #不如装饰器的方式清晰17 ancient usage of 181 kinds of property

Back to Top second, static method (Staticmethod)

Normally, all functions defined in the class (note that all that is said here, and self is nothing but a normal argument) is the object's binding method, and the object will automatically be called when the binding method is invoked. Pass yourself as a parameter to the first parameter of the method. There are two common ways to do this: static and Class methods, both of which are tailored to the class, but the instances are not to be used and no error is given.

is a normal function that is located in the namespace of the class definition and does not operate on any instance types, and Python has built the function Staticmethod to define the functions in the class as static methods

Class Foo:    def spam (x, y, z): #类中的一个函数, do not be confused, self and x what is not the difference is the parameter name        print (x, y, z)    spam=staticmethod (spam) # Make the spam function a static method

Based on the knowledge of the adorner previously learned, @staticmethod is equivalent to Spam=staticmethod (spam), so

Class Foo:    @staticmethod #装饰器    def spam (x, y, z):        print (x, y, z)

Using the Demo

Print (type Foo.spam) #类型本质就是函数Foo. Spam (All-in-one) #调用函数应该有几个参数就传几个参数f1 =foo () f1.spam (3,3,3) #实例也可以使用, but usually static methods are used for classes, The instance loses its automatic value-transfer mechanism in use ' <class ' function ' >2 33 3 '

Scenario: When writing a class, there are many different ways to create instances, and we have only one __init__ function, where static methods come into use.

Class Date:    def __init__ (self,year,month,day):        self.year=year        self.month=month        self.day=day    @staticmethod    def now (): #用Date the form to generate the instance, which uses the current time        t=time.localtime () #获取结构化的时间格式        return Date ( T.tm_year,t.tm_mon,t.tm_mday) #新建实例并且返回    @staticmethod    def tomorrow (): #用Date. Tomorrow () to produce an instance, The instance uses the time of Tomorrow        T=time.localtime (Time.time () +86400)        return Date (t.tm_year,t.tm_mon,t.tm_mday) a=date (' 1987 ', 11,27) #自己定义时间b =date.now () #采用当前时间c =date.tomorrow () #采用明天的时间print (a.year,a.month,a.day) print (B.year,b.month, B.day) print (c.year,c.month,c.day)

Back to Top Iii. class Methods (Classmethod)

Class methods are used for classes that use the class itself as an argument to the first parameter of a class method, and Python has built a function classmethod to define the function in the class as a class method

Class A:    x=1    @classmethod    def Test (CLS):        print (Cls,cls.x) class B (A):    x=2b.test () "Output:< Class ' __main__. B ' > 2 '

Application Scenarios:

Import Timeclass Date:    def __init__ (self,year,month,day):        self.year=year        self.month=month        Self.day=day    @staticmethod    def now ():        t=time.localtime ()        return Date (t.tm_year,t.tm_mon,t.tm_ Mday) class Eurodate (Date):    def __str__ (self):        return ' year:%s month:%s day:%s '% (Self.year,self.month, Self.day) E=eurodate.now () print (e) #我们的意图是想触发EuroDate. __str__, but the result is "output: <__main__. Date object at 0x1013f9d68> ' "

Because E is generated with the date class, it does not trigger eurodate.__str__ at all, and the solution is to use Classmethod

Import Timeclass Date:    def __init__ (self,year,month,day):        self.year=year        self.month=month        Self.day=day    # @staticmethod    # def now ():    #     T=time.localtime ()    #     return Date (T.tm_year, T.tm_mon,t.tm_mday)    @classmethod #改成类方法    def now (CLS):        t=time.localtime ()        return CLS (t.tm_year , T.tm_mon,t.tm_mday) #哪个类来调用, which class of CLS is used to instantiate class Eurodate (Date):    def __str__ (self):        return ' year:%s month:% S day:%s '% (self.year,self.month,self.day) E=eurodate.now () print (e) #我们的意图是想触发EuroDate. __str__, when E is produced by Eurodate, So, as we would like, "Output: year:2017 month:3 day:3"

It is important to note that static and class methods are prepared for classes, but they can be used if the instance is to be used, but it is easy to confuse the instance when it is called, not knowing what you are going to do.

X=e.now () #通过实例e去调用类方法也一样可以使用, same as static method print (x) "Output: year:2017 month:3 day:3"

Back to Top Iv. usage of additional knowledge points __str__
#__str__定义在类内部, you must return a string type, #什么时候会出发它的执行呢? When printing objects produced by this class, the execution class people is triggered:    def __init__ (self,name,age):        self.name=name        self.age=age    def __ Str__ (self):        return ' <name:%s,age:%s> '% (self.name,self.age) p1=people (' Egon ', ') print (p1) str (p1) #----- >P1.__STR__ ()

Python Basics----Properties, static methods (Staticmethod), class methods (Classmethod), __str__ usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.