Properties and methods of the various classes of the python, and chained calls

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
Type “copyright”, “credits” or “license()” for more information.

# Just listed the properties and methods are not enough to meet getattr (), setattr () and hasattr (), we can directly manipulate the state of an object:
class MyObject (Object):
Pass

MyObject = Shili ()
hasattr (Shili, 'x') # have attributes 'x' it?
False

What is shili.x # attribute (value)
Traceback (MOST Recent Last Call):
File "<pyshell. 6 #>", Line. 1, in
shili.x # what attribute (value)
AttributeError: 'the MyObject' Object attribute has NO 'X '

setattr (shili, 'y', 19) # set a property 'y'
hasattr (Shili, 'y') # have attributes 'y' do?
True

getattr (shili, 'y') # get property 'Y'
. 19

shili.y
19

# obj.y calling method is obtained getattr getattr (shili, 'y') value
getattr (shili, 'z', 404) # get property 'z', and if not, returns to the default value 404 for
404

hasattr (shili, 'power') # have attributes 'power' it?
False

# To the method of Example binding property is variable by way of example bart.xxx , or by self variable:

# If the Student class itself needs to bind a property it? Directly defined in the class is a class property attribute
class Student (Object):
name = 'Student'

Example # all classes can access to
S = Student ()
s.name
'Student'

Student.name
‘Student’

s.name = 'Michael' # instance is bound to a name attribute
s.name
'Michael'

# Masked class name attribute
Student.name
'Student'

del s.name # If you delete the instance name attribute
s.name
'Student'

# Use __slots__

Examples of a method for binding

def set_age (self, age): # define a function as an instance method
self.age = age

Import MethodType types from
s.set_age = MethodType (set_age, S) # instance is bound to a method
s.set_age (25) # call instance method
s.age # Test Results
25

To all instances # binding method, the method can bind to class:
DEF set_score (Self, Score):
self.score = Score

= MethodType Student.set_score (set_score, Student)
# bind to the class method, all instances can be called
s.set_score (100)
s.score
100

s2 = Student()
s2.set_score(99)
s2.score
99

Use __slots_ #
# class definitions when __slots__ define a special variable to limit the class instance attributes can be added to the
class Student (Object):
slots = ( 'name', 'Age') # tuple by definition allows name of the binding properties

s = Student () # create a new instance
s.name = 'Michael' # binding properties' name '
s.age = 25 # binding properties' Age
s.score = 99 # binding properties' Score'
Traceback (MOST Last Call Recent):
File "<pyshell # 73 is>", Line. 1, in
s.score = 99 # binding properties 'Score'
AttributeError: 'Student' Object attribute has NO 'Score'

#__slots__ attributes defined only for the current class instance acts on the subclass inherits does not work:
class (GraduateStudent) (Student):
Pass

g = GraduateStudent()
g.score = 9999
g.score
9999

# Use the @Property
# when binding properties, no way to check the parameters that you can easily change the results

set_score () method to set the score, get_score () to get the results

class Student(object):
def get_score(self):
return self._score
def set_score(self, value):
if not isinstance(value, int):
raise ValueError(‘score must be an integer!’)
if value < 0 or value > 100:
raise ValueError(‘score must between 0 ~ 100!’)
self._score = value

#Python built @property decorator is responsible for the property to become a method call:

class Student(object):
@property ##!!!
def get_score(self):
return self._score
@score.setter
def set_score(self, value):
if not isinstance(value, int):
raise ValueError(‘score must be an integer!’)
if value < 0 or value > 100:
raise ValueError(‘score must between 0 ~ 100!’)
self._score = value

Traceback (most recent call last):
File “<pyshell#100>”, line 1, in
class Student(object):
File “<pyshell#100>”, line 5, in Student
@score.setter
NameError: name ‘score’ is not defined

Student class (Object):
the @Property ## !!!
DEF Tscore (Self): ### into a get_ two names of the same name and set__ door not
return self._score
@ Tscore.setter
DEF Tscore (Self, value):
IF Not the isinstance (value, int):
The raise a ValueError ( 'Score MUST BE AN Integer!')
IF value <0 or value> 100:
The raise a ValueError ( '! Score MUST BETWEEN 0 ~ 100')
Self ._score = value

# To become a property getter method, only you need to add @property on it
# At this point, @ property itself has created another decorator @ score.setter to become a setter method for property assignment
S = Student ()
S .Tscore = 60

OK, the actual conversion is s.set_score (60)

s.Tscore
60

s.Tscore = 9999
Traceback (most recent call last):
File “<pyshell#109>”, line 1, in
s.Tscore = 9999
File “<pyshell#102>”, line 10, in Tscore
raise ValueError(‘score must between 0 ~ 100!’)
ValueError: score must between 0 ~ 100!

# Multiple inheritance.
Animal class (Object):
Pass

class Mammal(Animal):
pass

class Dog(Mammal):
pass

class Runnable(object)
SyntaxError: invalid syntax

class Runnable(object):
pass

class Runnable(object):
def run(self):
print(‘Running…’)

class Flyable(object):
def fly(self):
print(‘Flying…’)

class Dog(Mammal, Runnable):
pass

# Inherits e. This design is commonly referred MixIn.
Dog class (the Mammal, RunnableMixIn, CarnivorousMixIn):
Pass

Traceback (most recent call last):
File “<pyshell#147>”, line 1, in
class Dog(Mammal, RunnableMixIn, CarnivorousMixIn):
NameError: name ‘RunnableMixIn’ is not defined

#定制类
print(Student(‘Michael’))
Traceback (most recent call last):
File “<pyshell#156>”, line 1, in
print(Student(‘Michael’))
TypeError: object() takes no parameters

class Student(object):
def init(self, name):
self.name = name

print(Student(‘Michael’))
<main.Student object at 0x03572D30>

# Create an instance, print out a bunch, does not look good
class Student (Object):
DEF the init (Self, name):
self.name = name
DEF str (Self): #### custom class. Custom expressions
return 'Student Object (name:% S)'% the self.name

print(Student(‘Michael’))
Student object (name: Michael)

# Attentive friends will find direct knock variables do not print, print out or does not look good examples:
S = Student ( 'Michael')
S
< main .Student Object AT 0x03572D30>

# This is because the show is not directly __str variable call __ (), __ but __repr ()
# str () returns the string that the user can see, print can be called
S. Str

SyntaxError: unexpected indent

s.str
<bound method Student.str of <main.Student object at 0x03572D30>>

s.str()
‘Student object (name: Michael)’

Student(‘Michael’).str()
‘Student object (name: Michael)’

# Solution is to re-define a __repr __ (). But usually __str __ () and __repr __ () code is the same
class Student (Object):
DEF the init (Self, name):
the self.name = name
DEF STR (Self): #### custom classes. Custom expressions
return 'Student Object (name:% S)'% the self.name
the repr = STR

s = Student(‘Michael’)
s
Student object (name: Michael)

# Custom class __iter__, which returns an iterator objects
class Fib (Object):
DEF the init (Self):
self.a, self.b, = 0,. 1 # initializes two counters A, B
DEF ITER (Self):
return examples of self # iteration object itself, so to return to their
DEF next (Self):
self.a, self.b, self.b, =, + the self.b # self.a a calculated value
if self.a> 100000: # exit cycling conditions
raise StopIteration ();
the return self.a # return a value

for n in Fib():
print(n)

1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025

#getitem
Fib()[5]
Traceback (most recent call last):
File “<pyshell#192>”, line 1, in
Fib()[5]
TypeError: ‘Fib’ object does not support indexing

# It as a list to use or not, need to implement the __getitem __ () method of
class ffib (Object):
DEF getItem (Self, n-):
A, B =. 1,. 1
for X in Range (n-):
A, B = B, A + B
return A

f = ffib()
f[0]
1

# List but there is a magical slice method:
# ffib but for an error. The reason is __getitem __ () argument passed may be a int, it could be a slice object slice, so do judgment:
class ffib (Object):
DEF getItem (Self, the n-):
IF isinstance (the n-, int): # n is an index
A, B =. 1,. 1
for X in Range (n-):
A, B = B, A + B
return A
IF the isinstance (n-, slice): # n are slice
Start = n.start
STOP = n- .stop
IF IS None Start:
Start = 0
A, B =. 1,. 1
L = []
for X in Range (STOP):
IF X> = Start:
L.append (A)
A, B = B, A + B
return L

g=ffib()
f[0:5]
Traceback (most recent call last):
File “<pyshell#203>”, line 1, in
f[0:5]
File “<pyshell#195>”, line 4, in getitem
for x in range(n):
TypeError: ‘slice’ object cannot be interpreted as an integer

g[0:5]
[1]

ffib () [5:10]
[]

ffib () [: 10]
[1]

class ffib(object):

def __getitem__(self, n):
	if isinstance(n, int): # n 是索引
		a, b = 1, 1
		for x in range(n):
			a, b = b, a + b
		return a
	if isinstance(n, slice): # n 是切片
		start = n.start
		stop = n.stop
		if start is None:
			start = 0
		a, b = 1, 1
		L = []
		for x in range(stop):
			if x >= start:
				L.append(a)
			a, b = b, a + b
		return L

g=ffib()
g[0:5]
[1, 1, 2, 3, 5]

# The above is getitem__ achieve iteration,
#Python there is another mechanism that is to write a __getattr
() method returns a dynamic property
# getattr
class Student (Object):
DEF the init (Self):
self.name = 'Michael '
DEF getattr (Self, attr):
IF attr ==' Score ':
return 99

s = Student()
s.score
99

# Return function is also entirely possible:
class Student (Object):
DEF getattr (Self, attr):
IF attr == 'Age':
return the lambda: 25

# Just Called To become:
S = Student ()
s.age ()
25

# !! Note that only in the absence of property found only __getattr__ calls, existing attributes, such as name, does not look at the __getattr__.
s.abc
s.abc ()
Traceback (MOST Recent Last Call):
File "<242 pyshell #>", Line. 1, in
s.abc ()
TypeError: 'NoneType' IS Not Callable Object

# Noticed any calls as s.abc will return None, because __getattr__ we define default return is None.
Student class (Object):
DEF getattr (Self, attr):
IF attr == 'Age':
return the lambda: 25
The raise AttributeError ( '' Student 'has NO Object attribute'% S ''% attr)

s = Student()
s.scor
Traceback (most recent call last):
File “<pyshell#247>”, line 1, in
s.scor
File “<pyshell#245>”, line 5, in getattr
raise AttributeError(’‘Student’ object has no attribute’%s’’ % attr)
AttributeError: ‘Student’ object has no attribute’scor’

# Use fully dynamic __getattr__, we can write a chained calls
class Chain (Object):
DEF the init (Self, path = ''):
self._path = path
Print (path)
DEF getattr (Self, path):
Chain return ( '% S / S%'% (self._path, path))
DEF STR (Self):
return self._path
the repr = STR # returns the result to be able to create an instance method instead of returning properties

Chain().status.user.timeline.list

/status
/status/user
/status/user/timeline
/status/user/timeline/list
/status/user/timeline/list

# '' Is not a space meant
# '' is not omitted action
# So the first line is blank!
Chain class (Object):
DEF the init (Self, path = ''):
self._path path =

def __getattr__(self, path):
	print (path)
	return Chain('%s/%s' % (self._path, path))

def __str__(self):
	return self._path
__repr__ = __str__#为了创建实例就能返回结果而不是返回方法特性

Chain().status.user.timeline.list
status
user
timeline
list
/status/user/timeline/list

#__getattr__ return a dynamic attribute: Any call, _getattr__ default is to return None

class liejie(object):
def init(self,path=’’):
self.__path=path
print(’%s/%s’ % (self._path, path))

liejie().status
Traceback (most recent call last):
File “<pyshell#265>”, line 1, in
liejie().status
File “<pyshell#264>”, line 4, in init
print(’%s/%s’ % (self._path, path))
AttributeError: ‘liejie’ object has no attribute ‘_path’

# Do not find this attr (ie, Status)
# _getattr__ using any method he can to make calls

class liejie(object):
def init(self,path=’’):
self.__path=path

def __getattr__(self, path):
	return liejie('%s/%s' % (self._path, path))#调用自身初始化

. liejie () Status
Traceback (MOST Recent Call Last):
File "<pyshell # 275>", Line. 1, in
liejie () Status.
File "<pyshell # 274>", Line. 6, in getattr
return liejie ( '% s /% s'% (self._path , path)) # call initializes itself
File "<274 pyshell #>", Line. 6, in getattr
return liejie ( '% S / S%'% (self._path, path) ) calls itself to initialize #
File "<274 pyshell #>", Line. 6, in getattr
return liejie ( '% S / S%'% (self._path, path)) # call to initialize itself
[Previous line repeated 327 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object

liejie class (Object):
DEF the init (Self, path = ''):
self._path path = # more of a cross, why not?

def __getattr__(self, path):
	return liejie('%s/%s' % (self._path, path))#调用自身初始化

liejie (). Status
< main .liejie AT 0x00552830 Object>

liejie (). A
< main .liejie Object AT 0x005527D0>

class Chain(object):
def init(self, path=’’):
self._path = path

def __getattr__(self, path):
	
	return Chain('%s/%s' % (self._path, path))#调用自身初始化
def __str__(self):
	return self._path

liejie (). Status
< main .liejie AT 0x00552810 Object>

liejie().status()
Traceback (most recent call last):
File “<pyshell#285>”, line 1, in
liejie().status()
TypeError: ‘liejie’ object is not callable

class Chain(object):
def init(self, path=’’):
self._path = path

def __getattr__(self, path):

	return Chain('%s/%s' % (self._path, path))#调用自身初始化
def __str__(self):
	return self._path#这个是最终的返回结果
__repr__ = __str__#为了创建实例就能返回结果而不是返回方法特性

liejie (). Status
< main .liejie Object AT 0x005528B0>

Chain().status
/status

When ## when there is no call attributes, such as status, Python interpreter will attempt to call __getattr __ (self, 'status' ) to try to obtain property
# only if no properties found, it calls __getattr__,
# notice call any such s.abc will return None, __ getattr__ default is to return None. But the above have their own return repeated calls itself

Guess you like

Origin blog.csdn.net/qq_39306047/article/details/91854880