Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

How to inherit a python base class?

dir/
  |
  |___ __init__.py
  |
  |___ Base_class.py
  |
  |___ Subclass.py

__init__.py is empty(as mentioned here)


/* Base_class.py


class Employee:

    numOfEmployees = 0 # Pure class member, no need to override
    raiseAmount = 1.04 # Could not be pure class member, so, can it be overidden by object?
                           # Yes. make sense
                           # This is why we use self.raiseAmount in methods
    def __init__(self, firstName, lastName, pay):
        self.firstName = firstName
        self.lastName = lastName
        self.pay = pay
        self.email = firstName + '.' + lastName + '@email.com'

        Employee.numOfEmployees += 1

    def fullName(self):
        return '{} {}'.format(self.firstName, self.lastName)

    def appyRaise(self):
        self.pay = int(self.pay * self.raiseAmount)

        @classmethod
        def setRaiseAmt(cls, amount):
            cls.raiseAmount = amount

        @classmethod
        def createEmployee(cls, employeeStr):
            firstName, lastName, pay = employeeStr.split('-')
            return cls(firstName, lastName, pay)

        @staticmethod
        def isWorkDay(day):
            if day.weekday() == 5 or day.weekday() == 6:
                return False
            return True


emp1 = Employee('AAA', 'BBB', 50000)
emp2 = Employee('CCC', 'DDD', 40000)


print Employee.raiseAmount # 1.04
print emp1.raiseAmount     # 1.04
print emp2.raiseAmount     # 1.04

# Regular methods
emp1.fullName()          # Executing fullName(<__main__.Employee object at 0xb7dbef0c>) 
Employee.fullName(emp1)  # same as above 


# With classmethods, the class of the object instance is implicitly passed as the first argument instead of self.

Employee.setRaiseAmt(1.05) # class variable's cls member raiseAmount will get updated

print Employee.raiseAmount # 1.05
print emp1.raiseAmount     # 1.05
print emp2.raiseAmount     # 1.05

emp1.setRaiseAmt(1.05) # Invokes as, setRaise(<class '__main__.Employee'>,1.05)

# Application of class methods as constructors
employeeStr = 'John-Doe-70000'
newEmployee = Employee.createEmployee(employeeStr);

print newEmployee.email
print newEmployee.pay


# With static methods, neither self (the object instance) nor  cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:

emp1 = Employee('AAA', 'BBB', 50000)
emp2 = Employee('CCC', 'DDD', 40000)

import datetime
myDate = datetime.date(2016, 7, 10)

print emp1.isWorkDay(myDate) # Executing isWorkDay(myDate)

/* Subclass.py */

from  Base_class import Employee

class Developer(Employee):
    pass

Question:

On just inheriting Employee class:

> python Subclass.py

why this below output? How to inherit base class?

$ python Subclass.py
1.04
1.04
1.04
1.05
1.05
1.05
[email protected]
70000
False
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue you seem to be having is that when you import a module, all of its code is run, even if you're using from module import name syntax to just import a part of the module's contents. This is why you get the same output from running the Subclass.py file as you would if you ran Base_class.py.

If you don't want the testing code to run when you import the Base_class module, you should put it inside of an if __name__ == "__main__": block. The global variable __name__ is usually the name of the module (such as "Base_class"). It is "__main__" when you run a module as a script. Thus, testing for that string lets you run some code only when your module is the main script, and not when it's being imported by some other module.

You may also be confused about how subclasses see their parent class's attributes. This is somewhat magical in Python. When you look up an attribute on an instance, first the instance's own dictionary is checked, then it's class's dictionary, then the dictionaries of each of the base classes in its MRO (Method Resolution Order, generally the chain of parent classes in order unless you're doing complicated multiple inheritance). So an inherited attribute of Employee won't show up in Developer.__dict__ unless you explicitly set a new value for it on the Developer class.

As far as I can see, your code should work just fine if you create some Developer instances and call some of the methods they'll inherit. The only error in see is that the decorated methods in Employee are not indented the same as the other methods, but I suspect (based on the output you say you're getting) that that's an issue from copying the code to Stack Overflow, rather than a real bug. You may want to double check that you're not mixing spaces and tabs for your indents, which can lead to subtle errors that are hard to see (and mixing them is not allowed in Python 3).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...