A class and instance
1. The definition of property-related issues
- Class names are usually capitalized
- Form is defined as
class Student(object):
, Student behind the brackets indicate which class inheritance, if no suitable is to use the object.
- Some believe we must bind class attributes, by defining a
__init__
method, the first parameter of the method is always self, because the self is the point to create instances of itself.
- With the
__init__
method, create an instance in time, you can not pass a null parameter, you must pass the __init__
parameter matching method, but do not need to pass self, Python interpreter himself will pass in an instance variable.
- And compared to normal function, only a little different in function defined in the class, is the first argument is always an instance variable
self
, and when you call, do not pass this parameter.
2. Data Package
- By accessing the class defined inside the class property function, encapsulated data.
- A method is a function instance is bound, different from normal function, the method may directly access the data instance.
- And static different languages, Python allows any data variable bindings for instance, that is to say, for two instance variables, although they are different instances of the same class, but the variable names have may be different.
Second, limit access
- If you want external access inside the property is not to be put before the name of the property plus two underscores
__
, in Python, the instance variable names if the __
beginning, it becomes a private variable (private), can only access the internal , not external access.
- If you want to access external code, you can increase to Student class
get_name
and get_score
method for external access.
- If you have to modify the score, you can increase
set_name
method.
- Sometimes, you will see an instance variable names begin with an underscore, for example
_name
, such an instance variable names are available, but in accordance with the provisions are treated as private variables.
- Beginning with a double underscore instance variables are not necessarily not be accessed from outside it? In fact, no. Can not directly access
__name
because the Python interpreter outside the __name
variable changed _Student__name
, so, can still _Student__name
access the __name
variable
- But it is strongly recommended that you do not do it, because different versions of the Python interpreter may put __name into a different variable names. Overall it is, Python does not have any mechanism to stop you from doing bad things, all thanks to the conscious.
class Student(object):
def __init__(self, name, gender):
self.__name = name
self.__gender = gender
def get_name(self):
return self.__name
def get_gender(self):
return self.__gender
def set_gender(self, gender):
self.__gender = gender
bart = Student('Bart', 'male')
if bart.get_gender() != 'male':
print('测试失败!')
else:
bart.set_gender('female')
if bart.get_gender() != 'female':
print('测试失败!')
else:
print('测试成功!')
Third, inheritance, and polymorphism
- Inherited the biggest advantage is that, for the sub-category, access to the full functionality of the parent class.
- Of course, you can also increase the subclass methods, such as Dog class.
- When the parent class and subclass are present in the same way for subclasses override methods of the parent class, the code is running, there is always a subclass method calls, so that we get the benefit of another inheritance:
多态
- So, in the hierarchy, if the data type is an instance of a subclass of the type of data that it can also be seen as a parent. However, the reverse will not work
- Multi-state benefits, the caller just calls, regardless of the details, this is the famous
开闭原则
: open for extension: allow new Animal subclass; closed for modification: Animal depend not need to change the type of run_twice () and other functions.
- Static vs dynamic languages language for statically typed languages (such as Java), if the need to pass Animal type, the incoming object must be of type Animal or its subclasses, otherwise, you can not call the run () method; for Python such a dynamic language, you do not necessarily need to pass in Animal type. We just need to ensure that incoming object has a run () method on it.
Fourth, get the object information
- Use
type()
function can be used to determine the type of the object. Class returns the corresponding type.
- To determine if an object is a function, you can use
types
the constants defined in module
- Use
isinstance()
Analyzing Class type. And also determines whether or not a variable of a certain type,isinstance([1, 2, 3], (list, tuple)
- To get an object's properties and methods, you can use
dir()
the function. With getattr()
, , setattr()
, hasattr()
we can directly operate an object's state.
>>> class MyObject(object):
... def __init__(self):
... self.x = 9
... def power(self):
... return self.x * self.x
...
>>> obj = MyObject()
>>> hasattr(obj, 'x')
True
>>> obj.x
9
>>> hasattr(obj, 'y')
False
>>> setattr(obj, 'y', 19)
>>> hasattr(obj, 'y')
True
>>> getattr(obj, 'y')
19
>>> obj.y
19
>>> getattr(obj, 'z')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MyObject' object has no attribute 'z'
>>> getattr(obj, 'z', 404)
404
>>> hasattr(obj, 'power')
True
>>> getattr(obj, 'power')
<bound method MyObject.power of <__main__.MyObject object at 0x00000224FC11FF60>>
>>> fn = getattr(obj, 'power')
>>> fn
<bound method MyObject.power of <__main__.MyObject object at 0x00000224FC11FF60>>
>>> fn()
81
V. instance attributes and class attributes
- Examples of a method of binding property is variable by way of example or by
self
variable.
- If the
Student
class itself needs to bind a property can define attributes directly in the class, this property is the class attribute, in the final Student
class for all.
- In the preparation of procedures, do not for instance attributes and class attributes with the same name, because the instance property of the same name will shield the class attribute, but when you delete the instance attribute, and then use the same name, access to the It will be the class attribute