How to inherit a python base class?

2024/11/15 6:11:12
dir/||___ __init__.py||___ Base_class.py||___ Subclass.py

__init__.py is empty(as mentioned here)


/* Base_class.pyclass Employee:numOfEmployees = 0 # Pure class member, no need to overrideraiseAmount = 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 methodsdef __init__(self, firstName, lastName, pay):self.firstName = firstNameself.lastName = lastNameself.pay = payself.email = firstName + '.' + lastName + '@email.com'Employee.numOfEmployees += 1def fullName(self):return '{} {}'.format(self.firstName, self.lastName)def appyRaise(self):self.pay = int(self.pay * self.raiseAmount)@classmethoddef setRaiseAmt(cls, amount):cls.raiseAmount = amount@classmethoddef createEmployee(cls, employeeStr):firstName, lastName, pay = employeeStr.split('-')return cls(firstName, lastName, pay)@staticmethoddef isWorkDay(day):if day.weekday() == 5 or day.weekday() == 6:return Falsereturn Trueemp1 = 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 updatedprint Employee.raiseAmount # 1.05
print emp1.raiseAmount     # 1.05
print emp2.raiseAmount     # 1.05emp1.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 Employeeclass 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
Answer

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).

https://en.xdnf.cn/q/119691.html

Related Q&A

Validation for int(input()) python

def is_digit(x):if type(x) == int:return Trueelse:return Falsedef main():shape_opt = input(Enter input >> )while not is_digit(shape_opt):shape_opt = input(Enter input >> )else:print(it work…

How to get data out of a def function in python [duplicate]

This question already has answers here:How do I get ("return") a result (output) from a function? How can I use the result later?(4 answers)Closed 1 year ago.Trying to simplify lots of repe…

Calculating RSI in Python

I am trying to calculate RSI on a dataframedf = pd.DataFrame({"Close": [100,101,102,103,104,105,106,105,103,102,103,104,103,105,106,107,108,106,105,107,109]})df["Change"] = df["…

Pandas groupwise percentage

How can I calculate a group-wise percentage in pandas?similar to Pandas: .groupby().size() and percentages or Pandas Very Simple Percent of total size from Group by I want to calculate the percentage…

How to deal with large json files (flattening it to tsv) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 3 years ago.Improve…

How can I find max number among numbers in this code?

class student(object):def student(self):self.name=input("enter name:")self.stno=int(input("enter stno:"))self.score=int(input("enter score:"))def dis(self):print("nam…

Assert data type of the values of a dict when they are in a list

How can I assert the values of my dict when they are in a list My_dict = {chr7: [127479365, 127480532], chr8: [127474697, 127475864], chr9: [127480532, 127481699]}The code to assert this assert all(isi…

Loading tiff images in fiftyone using ipynp

I am trying to load tiff images using fiftyone and python in ipynb notebook, but it just doesnt work. Anyone knows how to do it?

Regular expression to match the word but not the word inside other strings

I have a rich text like Sample text for testing:<a href="http://www.baidu.com" title="leoshi">leoshi</a>leoshi for details balala... Welcome to RegExr v2.1 by gskinner.c…

Make one image out of avatar and frame in Python with Pillow

If I haveandneed to getdef create_avatar(username):avatar, frame, avatar_id = get_avatar(username)if avatar is not None and frame is not None:try:image = Image.new("RGBA", size)image.putalpha…