[Python learning journey] --- Packaging and reflection (knowledge of class, object-oriented three characteristics: inheritance - polymorphism - Package)

The first layer encapsulating #: define a class 
# encapsulating the second layer: distinguish between inside and outside, some properties can only be used internally, not externally


class the Name:

__A = 'you are a pig' # variable encapsulation A
DEF the __init __ (Self, name):
Self. name = name

DEF get_name (Self):
Print ( 'my name S%'% self.name)


N1 = the name ( 'Chen Yuxia')
Print (the name .__ dict__) # View class attributes dictionary
print (n1._Name__a) # can this way call __a, there is no real package

# genuine package: distinction between inside and outside, to provide users with an interface to access a function call, the internal logic to achieve, can not be known outside of
class Room:
DEF __init __ (Self, name, Leng, width):
self.name name =
Self .__ = Leng Leng
Self .__ width = width
DEF GET (Self): # interface function, let's call the hidden attribute external
return Leng * Self Self .__ .__ width

r1 = Room ( 'toilet' , 100,50)
Print (r1.get ()) # external function by calling get


#Results of the:

{'__module__': '__main__', '_Name__a': '你是猪', '__init__': <function Name.__init__ at 0x00000232CEB08EA0>, 'get_name': <function Name.get_name at 0x00000232CEB08E18>, '__dict__': <attribute '__dict__' of 'Name' objects>, '__weakref__': <attribute '__weakref__' of 'Name' objects>, '__doc__': None}
你是猪
5000

# Detection program has its own function 
class Room:
DEF __init __ (Self, name, Leng, width):
self.name name =
Self .__ = Leng Leng
Self .__ width = width
DEF GET (Self): # interface functions, let's external call hidden attribute
return Leng Self .__ * Self .__ width

r1 = Room ( 'WC', 100,50)

Print (the hasattr (r1, 'name')) example # r1 detects whether there is the attribute name
print (getattr (r1, 'name')) # Get the value of the instance attribute
setattr (r1, 'name', ' bedroom') # instance attribute modification value
Print (r1.name)
delattr (R1, 'name') delete the value of the instance attribute #
Print (R1 .__ dict__ magic)

# hasattr benefits of using
class the FTP:
DEF the __init __ (Self, addr):
Print ( "connecting to the server S%" addr%)
self.addr addr =

F1 = the FTP ( '1.1.1.1')
if hasattr (FTP, 'get' ): # FTP determines whether there is a get function
a = getattr (FTP, 'get ') # available is acquired function address
a () # Run function
the else:
Print ( "perform additional logic" )


# The results:

  True
  toilet
  bedroom
 { '_Room__leng': 100, ' _Room__width': 50}
 connecting to the server 1.1.1.1
 perform other logic























Guess you like

Origin www.cnblogs.com/chenyuxia/p/12147069.html