初始化类的属性的2种写法:
如下要注意python对文件名称、类、方法名的命名
方式一:原始的定义
class User1:
# 初始化账号和密码
def __init__(self):# 账号和密码self.__username = Noneself.__password = Nonedef getnsername(self):return self.__usernamedef getpassword(self):return self.__passworddef setusername(self, username):self.__username = usernamedef setpassword(self, password):self.__password = passwordif __name__ == '__main__':usr1 = User1()usr1.setusername("admin")usr1.setpassword("8888")print(usr1.getnsername())print(usr1.getpassword())
方式二:可以跳过pytest的限制(pytest的对类的方法不能有init()方法)
class User:
# 初始化类的属性:账号、密码
__username = None
__password = Nonedef getname(self):return self.__usernamedef getpassword(self):return self.__passworddef setusername(self, username):self.__username = usernamedef setpassword(self, password):self.__password = passwordif __name__ == '__main__':usr = User()usr.setusername("admin")usr.setpassword("8888")print(usr.getname())print(usr.getpassword())
三、pytest的命名规则:
1.模块名必须以test_开头或者以_test结尾
2.测试类必须以Test开头,并且不能有init方法
3.测试方法以test开头
四、方式二和java的对类的定义是一样的:
创建User类:(可以对比其相似度)
public class User {private String username;private String password;public User() {super();}public String getUsername() {return username;}public String getPassword() {return password;}public void setUsername(String username) {this.username = username;}public void setPassword(String password) {this.password = password;}public User(String username, String password) {this.username = username;this.password = password;}@Overridepublic String toString() {return "User{" +"username='" + username + '\'' +", password='" + password + '\'' +'}';}public static void main(String[] args) {User user = new User();user.setUsername("admin");user.setPassword("8888");System.out.println(user.getUsername());System.out.println(user.getPassword());}}